package ex01.pyrmont;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Response {

	private static final int BUFFER_SIZE = 1024;
	Request request;
	OutputStream outputStream;
	
	public Response(OutputStream out) {
		outputStream = out;
	}
	
	public void sendStaticResource() throws IOException {
		
		byte[] bs = new byte[BUFFER_SIZE];
		FileInputStream fileInputStream = null;
		File file = new File(HttpServer.WEB_ROOT, request.getUri());
		if (file.exists()) {
			fileInputStream = new FileInputStream(file);
			int ch = fileInputStream.read(bs, 0, BUFFER_SIZE);
			while (ch != -1) {
				outputStream.write(bs, 0, ch);
				ch = fileInputStream.read(bs, 0, BUFFER_SIZE);
			}
		} else {
			StringBuffer errMessage = new StringBuffer();
			errMessage.append("HTTP/1.1 404 File Not Found\r\n").append("Content-Type: text/html\r\n").append("Content-Length: 23\r\n\r\n")
				.append("<h1>File Not Found</h1>");
			outputStream.write(errMessage.toString().getBytes());
		}
		if (fileInputStream != null) {
			fileInputStream.close();
		}
	}
	
	public OutputStream getWriter() {
		return outputStream;
	}
	
	public Request getRequest() {
		return request;
	}
	
	public void setRequest(Request request) {
		this.request = request;
	}
	
	// TODO 下面的方法还没有实现
	public String getCharacterEncoding() {
		
		return null;
	}
}
